package com.zlf.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zlf.mapper.UserMapper;
import com.zlf.po.User;
import com.zlf.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Service
public class UserServiceImpl implements UserService{

    private final BCryptPasswordEncoder passwordEncoder;
    @Autowired
    public UserServiceImpl(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUserByIdByPass(User user) {
        if(!passwordEncoder.matches(user.getPassword(),userMapper.getHashedPasswordById(user.getUserId())))
        {
            return null;
        }
        else{
            User user1=userMapper.getUserByIdByPass(user);
            user1.setPassword("unknown");
            return user1;
        }
    }

    @Override
    public User getUserById(String userId) {
        User user=userMapper.getUserById(userId);
        user.setPassword("unknown");
        return user;
    }

    @Override
    public int saveUser(User user) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode1 = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode1);
        String img="";
        user.setUserImg(img);
        return userMapper.saveUser(user);
    }

    @Override
    public int updateNickname(String userId, String newNickname) {
        return userMapper.updateNickname(userId,newNickname);
    }

    @Override
    public int uploadAvatarBase64(String userId, String avatarBase64) {
        String  avatar=avatarBase64.replaceAll( " ","+");
        return userMapper.uploadAvatarBase64(userId,avatar);
    }

    @Override
    public int updateUserPass(String newPassword,String userId,String oldPassword){
        if(!passwordEncoder.matches(oldPassword,userMapper.getHashedPasswordById(userId)))
        {
            return 0;
        }
        else
        {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(newPassword);
            return userMapper.updateUserPass(encode, userId);
        }
    }

}
